/*
 * Copyright (c) 2014-2015 Luca Agostini, Alessandro Cantini, Alessandro Dignani
 *
 * This file is part of MeteoCal.
 *
 * MeteoCal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package it.polimi.se2.agostini_cantini_dignani.meteocal.business;

import it.polimi.se2.agostini_cantini_dignani.meteocal.entity.User;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import static org.junit.Assert.*;

@RunWith(Arquillian.class)
public class UserManagerIT {

	private static final String VALID_EMAIL = "usermanagerit@example.com";
	private static final String INVALID_EMAIL = "not an email";
	private static final String VALID_PASSWORD = "mypassword";
	private static User user;

	@EJB
	private UserManager cut;

	@PersistenceContext
	private EntityManager em;

	@Deployment
	public static WebArchive createArchiveAndDeploy() {
		return ShrinkWrap.create(WebArchive.class)
				.addPackage(UserManager.class.getPackage())
				.addPackage(User.class.getPackage())
				.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
				.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
	}

	@BeforeClass
	public static void setUpClass() {
		user = new User();
		user.setPassword(VALID_PASSWORD);
		user.setEmail(VALID_EMAIL);
	}

	@Test
	public void testCreateUser() {
		cut.createUser(user);

		User foundUser = em.find(User.class, VALID_EMAIL);

		assertNotNull(foundUser);
		assertEquals(user, foundUser);
		assertEquals(user.getEmail(), foundUser.getEmail());
		assertEquals(user.getPassword(), foundUser.getPassword());
		assertNotNull(foundUser.getCalendar());
		assertEquals(foundUser, foundUser.getCalendar().getOwner());
		assertEquals(user.getCalendar(), foundUser.getCalendar());
	}

	@Test
	public void testInvalidEmail() {
		user.setEmail(INVALID_EMAIL);

		boolean ejbExceprion = false;
		try {
			cut.createUser(user);
		} catch (EJBException e) {
			ejbExceprion = true;
		}
		assertTrue(ejbExceprion);
		assertNull(em.find(User.class, INVALID_EMAIL));
	}
}